const Controller = require('egg').Controller;

class LockController extends Controller {
    //验证用户登录
    async userLogin() {
        const loginInfo = this.ctx.request.body;
        const isExistsUser = await this.ctx.model.User.count({
            where: { userId: loginInfo.userId }
        });
        if (!isExistsUser) {
            throw Error(this.ctx.__('the user is not exists'))
        }
        let loginVerify = await this.ctx.model.User.findOne({
            where: {
                userId: loginInfo.userId,
                passWord: loginInfo.passWord
            }
        })
    }

    async validLockPermission(lockId, user) {
        const currentTime = new Date();
        const type = user.type || 'TENANT';
        const { userId, hotelId } = user;
        let op = {
            where: {
                lockId, userId, type, hotelId,
                startTime: { $lte: currentTime },
                endTime: { $gte: currentTime }
            }
        };
        if (type === 'MANAGER') {
            op = {
                where: {
                    lockId, userId, type, hotelId
                }
            };
        }
        const isPermission = await this.ctx.model.LockPermission.count(op);
        if (!isPermission) {
            throw Error(this.ctx.__('the user has no permission of the lock'));
        }
    }

    async getPacketOfTime() {
        const lockId = this.ctx.params.lock_id;
        const userId = this.ctx.query.userId;
        const type = this.ctx.query.type;
        const hotelId = this.ctx.query.hotelId;
    }

    async getPacketOfTime() {
        const lockId = this.ctx.params.lock_id;
        const userId = this.ctx.query.userId;
        const type = this.ctx.query.type;
        const hotelId = this.ctx.query.hotelId;
        await this.validLockPermission(lockId, {userId, type, hotelId});
        const buf = Buffer.alloc(19).fill(0x00);
        buf.writeUInt8(0x00, 10);
        buf.writeUInt32LE(Math.floor(Date.now() / 1000), 11);
        buf.writeUInt8(0x08, 15);
        const packetbuf = this.ctx.helper.lockEncode(lockId, buf);
        this.ctx.body = {
            packets: [packetbuf.toString('base64')]
        };
    }
}